package dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import domain.LoginLog;
import domain.User;

public class LogDaoImpl implements LogDao {
	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
//	@Override
//	public void insertLoginLog(String acc){
//		Session session = sessionFactory.getCurrentSession();
//		Query q = session.createQuery("from User where account = ?");
//		q.setString(0, acc);
//		List userList = q.list();
//		User loginUser = null;
//		if(userList.size()>=1)
//			loginUser  = (User) userList.get(0);
//		LoginLog ll = new LoginLog();
//		ll.setUser(loginUser);
//		ll.setLoginTime(new Date());
////		if(loginUser.getId())
//		ll.setId(loginUser.getId());
//		session.saveOrUpdate(ll);
//	}
//	
	@Override
	public Date getDate(User u){
		int userId = u.getId();
		Session session=sessionFactory.openSession();
		Query q = session.createQuery("from LoginLog where LOGINUSER_ID = ?");
		List temp = q.setInteger(0, userId).list();
		Date d = new Date();
		if(temp.size()>=1){
			LoginLog ll = (LoginLog)temp.get(0);
			d = ll.getLoginTime();
		}
		return d;
	}
	/*插入登入日志
	 * 	(non-Javadoc)
	 * @see dao.LogDao#insertLoginLog(java.lang.String)
	 */
		@Override
		public void insertLoginLog(String acc){
			Session session = sessionFactory.getCurrentSession();
			Query q = session.createQuery("from User where account = ?");
			q.setString(0, acc);
			List userList = q.list();
			User loginUser = null;
			if(userList.size()>=1)
				loginUser  = (User) userList.get(0);
			LoginLog ll = new LoginLog();
			ll.setUser(loginUser);
			ll.setLoginTime(new Date());
			q = session.createQuery("from LoginLog where id = ?");
			List temp = q.setInteger(0, loginUser.getId()).list();
			ll.setId(loginUser.getId());
			if(temp.size()>=1){
				session.evict(temp.get(0));
				session.update(ll);
			}
			else{
				session.save(ll);
			}
			
		}
		
}
